package com.whacos.modules.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.entity.Tree;
import com.whacos.common.enums.Constant;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.ObjectUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.system.entity.SysMenu;
import com.whacos.modules.system.service.SysMenuService;
import com.whacos.modules.system.vo.SysMenuVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiongdun
 * @description SysMenuController
 * @since 2018/11/17 17:11
 */
@Controller
@RequestMapping("/sys/menu")
@Slf4j
public class SysMenuController extends BaseController {

    private static final String PREFIX = "sys/menu";

    @Autowired
    private SysMenuService sysMenuService;

    // @Log("跳转到菜单列表")
    @GetMapping()
    @RequiresPermissions("sys:menu:menu")
    public String menu() {
        return PREFIX + "/menu";
    }

    // @Log("查询菜单列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("sys:menu:menu")
    public List<SysMenuVO> list(SysMenuVO sysMenuVO) {
        List<SysMenuVO> sysMenuVOList = new ArrayList<>();
        try {
            // 请求参数
            // 查询数据
            List<SysMenu> sysMenuList = sysMenuService.list(Wrappers.lambdaQuery(new SysMenu())
                    .eq(StringUtils.isNotEmpty(sysMenuVO.getName()), SysMenu::getMenuName, sysMenuVO.getName())
                    .eq(ObjectUtils.isNotEmpty(sysMenuVO.getType()), SysMenu::getMenuType, sysMenuVO.getType())
                    .orderByAsc(SysMenu::getOrderNum));
            // 返回结果
            sysMenuList.forEach(sysMenuReturn -> {
                SysMenuVO sysMenuVOReturn = new SysMenuVO();
                BeanUtils.copyProperties(sysMenuReturn, sysMenuVOReturn);
                sysMenuVOList.add(sysMenuVOReturn);
            });

        } catch (Exception e) {
            log.error("查询菜单列表异常，异常原因：" + e.getMessage(), e);
        }
        return sysMenuVOList;
    }

    // @Log("跳转添加菜单信息")
    @GetMapping("/add/{parentId}")
    @RequiresPermissions("sys:menu:add")
    public String add(Model model, @PathVariable("parentId") Long parentId) {
        model.addAttribute("parentId", parentId);
        if (ObjectUtils.isEmpty(parentId) || parentId == 0) {
            model.addAttribute("parentName", "根目录");
        } else {
            model.addAttribute("parentName", sysMenuService.getById(parentId).getMenuName());
        }
        return PREFIX + "/add";
    }

    // @Log("跳转编辑菜单信息")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("sys:menu:edit")
    public String edit(Model model, @PathVariable("id") Long id) {
        SysMenu sysMenu = sysMenuService.getById(id);
        Long parentId = sysMenu.getParentId();
        model.addAttribute("parentId", parentId);
        if (ObjectUtils.isEmpty(parentId) || parentId == 0) {
            model.addAttribute("parentName", "根目录");
        } else {
            model.addAttribute("parentName", sysMenuService.getById(parentId).getMenuName());
        }
        model.addAttribute("sysMenu", sysMenu);
        return PREFIX + "/edit";
    }

    @Log("保存菜单信息")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("sys:menu:add")
    public ResponseVO save(SysMenuVO sysMenuVO) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            SysMenu sysMenu = new SysMenu();
            BeanUtils.copyProperties(sysMenuVO, sysMenu);
            // 保存结果
            sysMenu.createdData(this.getUserId());
            if (sysMenuService.save(sysMenu)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("保存菜单信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(1, "保存失败");
        }
        return ResponseVO.error(1, "保存失败");
    }

    @Log("更新菜单信息")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("sys:menu:edit")
    public ResponseVO update(SysMenuVO sysMenuVO) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            SysMenu sysMenu = new SysMenu();
            BeanUtils.copyProperties(sysMenuVO, sysMenu);
            // 保存结果
            sysMenu.updatedData(this.getUserId());
            if (sysMenuService.updateById(sysMenu)) {
                return ResponseVO.success();
            } else {
                return ResponseVO.error(1, "更新失败");
            }
        } catch (Exception e) {
            log.error("更新菜单信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(1, "更新失败");
        }
    }

    @Log("删除菜单信息")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("sys:menu:remove")
    public ResponseVO remove(@RequestParam(value = "id") Long id) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (sysMenuService.removeById(id)) {
                return ResponseVO.success();
            } else {
                return ResponseVO.error(1, "删除失败");
            }
        } catch (Exception e) {
            log.error("删除菜单信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(1, "删除失败");
        }
    }

    // @Log("获取菜单树信息")
    @GetMapping("/tree")
    @ResponseBody
    public Tree<SysMenu> tree() {
        return sysMenuService.getTree();
    }

    // @Log("按 roleId 获取菜单树信息")
    @GetMapping("/tree/{roleId}")
    @ResponseBody
    public Tree<SysMenu> tree(@PathVariable("roleId") Long roleId) {
        return sysMenuService.getTreeByRoleId(roleId);
    }
}
